<template>
    <div class="chat-main">
        <!-- 消息容器 -->
        <div class="chat-window">
            <div class="message-container" ref="messageContainer">
                <div v-if="messages.length === 0" class="empty-state">暂无消息</div>

                <div v-for="(msg, index) in messages" :key="index" class="message-item">
                    <!-- 用户名头部 -->
                    <div class="message-header">
                        <span class="sender" :class="{ user: msg.role === 'user', ai: msg.role !== 'user' }">
                            {{ msg.role === 'user' ? '你' : 'AI' }}
                        </span>
                    </div>

                    <!-- 显示 thinking 折叠区域 -->
                    <div v-if="msg.thinking" class="thinking-block">
                        <details>
                            <summary>点击查看思考过程</summary>
                            <pre class="thinking-content">{{ msg.thinking }}</pre>
                        </details>
                    </div>

                    <!-- Markdown 内容 -->
                    <div v-if="msg.content" class="content markdown-content"
                        :class="{ user: msg.role === 'user', ai: msg.role !== 'user' }"
                        v-html="renderMarkdown(msg.content)">
                    </div>
                </div>

                <!-- 流式思考 -->
                <div v-if="streamingThinking" class="message-item">
                    <div class="sender">AI(思考)</div>
                    <div class="thinking-content ai">
                        {{ streamingThinking }}
                    </div>
                </div>

                <!-- 流式回复 -->
                <div v-if="streamingMessage" class="message-item">
                    <div class="sender">AI</div>
                    <div class="content ai streaming-typing markdown-content" v-html="renderMarkdown(streamingMessage)">
                    </div>
                </div>
            </div>

            <!-- 输入框 -->
            <div class="input-area">
                <div class="input-wrapper">
                    <el-input v-model="inputMessage" placeholder="输入你的问题..." @keyup.enter="sendMessageTOLLM" clearable
                        type="textarea" :rows="4" :autosize="{ minRows: 2, maxRows: 6 }" />
                    <el-button @click="sendMessageTOLLM" class="send-button">发送</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { getMessage, sendMessage, startStreamReply } from '@/api/chat'
import marked from 'marked'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'

const route = useRoute()
const sessionId = ref('1')
const messages = ref([])
const inputMessage = ref('')
const streamingMessage = ref('')
const messageContainer = ref(null)
const streamingThinking = ref('')

// 渲染 Markdown 函数（带代码高亮）
const renderMarkdown = (text) => {
    marked.setOptions({
        highlight: function (code, lang) {
            return hljs.highlight(code, { language: lang }).value
        }
    })
    return DOMPurify.sanitize(marked.parse(text || ''))
}

// 滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        if (messageContainer.value) {
            messageContainer.value.scrollTop = messageContainer.value.scrollHeight
        }
    })
}

// 获取历史消息
const fetchMessages = async () => {
    try {
        console.log('获取历史消息...')
        console.log('sessionId:', sessionId.value)
        const res = await getMessage(sessionId.value)
        console.log('历史消息:', res)
        if (res.code === 100) {
            messages.value = res.data
            scrollToBottom()
        }
    } catch (e) {
        console.error('获取消息失败:', e)
    }
}

// 发送消息
const sendMessageTOLLM = async () => {
    const content = inputMessage.value.trim()
    if (!content || !sessionId.value) return

    // 添加用户消息
    messages.value.push({ role: 'user', content })
    inputMessage.value = ''
    scrollToBottom()

    try {
        await sendMessage('qwen3:4b', content, sessionId.value, true)
        startStream()
    } catch (e) {
        console.error('发送失败:', e)
    }
}

let eventSource = null

const startStream = () => {
    let currentContent = ''
    let currentThinking = ''

    if (eventSource) {
        eventSource.close()
    }

    eventSource = startStreamReply(
        sessionId.value,
        (event) => {
            try {
                const data = JSON.parse(event.data)

                if (data.done === "true") {
                    if (currentContent) {
                        messages.value.push({ role: 'assistant', content: currentContent })
                    }
                    if (currentThinking && !streamingThinking.value) {
                        messages.value.push({ role: 'assistant', thinking: currentThinking })
                    }
                    currentContent = ''
                    currentThinking = ''
                    streamingMessage.value = ''
                    streamingThinking.value = ''
                    eventSource.close()
                    return
                }

                if (data.message?.content) {
                    currentContent += data.message.content
                    streamingMessage.value = currentContent
                    scrollToBottom()
                } else if (data.message?.thinking) {
                    currentThinking += data.message.thinking
                    streamingThinking.value = currentThinking
                }
            } catch (e) {
                console.error('解析流式数据失败:', e)
            }
        },
        (err) => {
            console.error('SSE错误:', err)
        },
        () => {
            if (currentContent) {
                messages.value.push({ role: 'assistant', content: currentContent })
            }
            if (currentThinking) {
                messages.value.push({ role: 'assistant', thinking: currentThinking })
            }
            currentContent = ''
            currentThinking = ''
            streamingMessage.value = ''
            streamingThinking.value = ''
        }
    )
}

// 监听路由变化
watch(
    () => route.params.sessionId,
    (newId) => {
        sessionId.value = '1'
        messages.value = []
        fetchMessages()
    },
    { immediate: true }
)

onMounted(() => {
    fetchMessages()
})
</script>

<style lang="scss" scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap');

.chat-main {
    display: flex;
    height: 100vh;
    justify-content: flex-start;
    margin: auto;
    text-align: left;
    font-family: 'Inter', sans-serif;
}

.chat-window {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 80vh;
    max-width: 100%;
    margin: auto;
    padding: 1rem;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(31, 38, 135, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(16px) saturate(1.5);
    transition: all 0.3s ease;

    @media (max-width: 768px) {
        padding: 0.5rem;
        border-radius: 12px;
    }
}

.message-container {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
    background-color: #f9f9f9;


    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
    }
}

.empty-state {
    text-align: center;
    color: #999;
    margin-top: 2rem;
}

.input-area {
    padding: 0.75rem 1rem;
    background-color: #fff;
    border-top: 1px solid #eaeaea;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);

    .input-wrapper {
        display: flex;
        gap: 10px;

        .el-textarea {
            flex: 1;

            .el-textarea__inner {
                resize: none;
                padding: 12px 20px;
                font-size: 1rem;
                line-height: 1.5;
                overflow-y: auto;
                border: none;
                outline: none;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
                transition: all 0.3s ease;
            }

            .el-textarea__inner:focus {
                box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
            }
        }

        .send-button {
            flex: 0 0 100px;
            background-color: #409EFF;
            color: white;
            border-radius: 30px;
            transition: background-color 0.3s ease;

            &:hover {
                background-color: #337ecc;
            }
        }
    }
}

.message-item {
    animation: fadeIn 0.3s ease-in-out;
    margin-bottom: 1.5rem;
}

.message-header {
    display: flex;
    justify-content: flex-start;

    margin-bottom: 4px;

    .sender {
        font-size: 0.85rem;
        font-weight: bold;
        color: #666;
        padding: 0 10px;
        border-radius: 12px;
        transition: all 0.3s ease;
    }

    .sender.user {
        background-color: #409EFF;
        color: white;
        align-self: flex-end;
        justify-content: flex-end;
    }

    .sender.ai {
        background-color: #e0e0e0;
        color: #333;
    }
}

.content {
    max-width: 70%;
    padding: 0.75rem 1rem;
    border-radius: 12px;
    word-wrap: break-word;
    font-size: 1rem;
    line-height: 1.5;
    transition: background-color 0.3s;
}

.content.user {
    background-color: #409EFF;
    color: white;
    align-self: flex-end;
    margin-left: auto;
    border-top-right-radius: 4px;
}

.content.ai {
    background-color: #ffffff;
    color: #333;
    margin-right: auto;
    border-top-left-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.streaming-typing::after {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    margin-left: 4px;
    background: #333;
    border-radius: 50%;
    vertical-align: middle;
    animation: typingDots 1.2s infinite;
}

.thinking-block {
    max-width: 70%;
    margin-right: auto;
    background-color: #f8f8f8;
    border-left: 4px solid #ddd;
    padding: 0.75rem 1rem;
    border-radius: 8px;
    font-size: 0.9rem;

    summary {
        font-weight: bold;
        color: #555;
        cursor: pointer;
    }

    pre {
        white-space: pre-wrap;
        word-wrap: break-word;
        background-color: #f0f0f0;
        padding: 0.5rem;
        margin-top: 0.5rem;
        border-radius: 4px;
        overflow-x: auto;
    }
}

.markdown-content {
    p {
        margin: 0.5em 0;
    }

    pre {
        background-color: #f0f0f0;
        padding: 0.75rem;
        border-radius: 6px;
        overflow-x: auto;
    }

    code {
        background-color: #eee;
        padding: 0.2em 0.4em;
        border-radius: 4px;
        font-family: monospace;
    }

    blockquote {
        border-left: 4px solid #409eff;
        padding-left: 1rem;
        color: #666;
        margin-left: 0;
    }

    ul,
    ol {
        padding-left: 1.5rem;
        margin: 0.5rem 0;
    }
}

@keyframes typingDots {
    0% {
        transform: scale(0);
        opacity: 0;
    }

    50% {
        transform: scale(1);
        opacity: 1;
    }

    100% {
        transform: scale(0);
        opacity: 0;
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>